<template>
  <el-card class="box-card" shadow="never" style="margin-bottom: 10rem !important;">
    <div slot="header" class="clearfix"
         style="display: flex; align-items: flex-start; justify-content: space-between; ">
      <span>{{ kpiPartyVO.title }}赛福斯特公司党支部党建考核KPI</span>
    </div>
    <!--kpi表-->
    <el-table :data="showKpiTable ? primaryIndicatorVOS : []" size="mini" border
              tooltip-effect="dark" :span-method="kpiSpanMethod" header-cell-class-name="headerCell"
              header-row-class-name="headerRow" @cell-click="viewKpiItemDetail" :cell-style="cellStyle">
      <el-table-column label="党建KPI">
        <template #header>
          <span>党建KPI</span>
          <el-button
              type="text"
              size="mini"
              @click="showKpiTable = !showKpiTable"
          >
            <i :class="showKpiTable ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
            {{ showKpiTable ? '收起' : '展开' }}
          </el-button>
        </template>
        <el-table-column label="序号"
                         type="index"
                         min-width="5%" align="center"></el-table-column>
        <el-table-column min-width="15%"
                         prop="primaryIndicator"
                         label="一级指标"></el-table-column>
        <el-table-column min-width="20%"
                         prop="indicatorPoint"
                         label="指标要点"></el-table-column>
        <el-table-column prop="indicatorDetail" label="具体内容" min-width="47%"></el-table-column>
        <el-table-column min-width="10%"
                         prop="endTime"
                         label="计划完成时间"></el-table-column>
        <el-table-column min-width="8%"
                         prop="complete"
                         label="完成率"></el-table-column>
        <el-table-column min-width="5%" prop="personInCharge" label="负责人"></el-table-column>
      </el-table-column>
    </el-table>
    <!--plan表-->
    <el-table :data="showKpiPlanTable ? primaryIndicatorPlanVOS : []" size="min" border
              tooltip-effect="dark" :span-method="planSpanMethod" header-cell-class-name="headerCell"
              header-row-class-name="headerRow"
              style="width: 100%" @cell-click="viewKpiItemDetail" :cell-style="cellStyle">
      <el-table-column label="党建工作计划">
        <template #header>
          <span>党建工作计划</span>
          <el-button
              type="text"
              size="mini"
              @click="showKpiPlanTable = !showKpiPlanTable"
          >
            <i :class="showKpiPlanTable ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
            {{ showKpiPlanTable ? '收起' : '展开' }}
          </el-button>
        </template>
        <el-table-column label="序号"
                         type="index"
                         min-width="5%" align="center">
        </el-table-column>

        <el-table-column min-width="15%"
                         prop="primaryIndicatorPlan"
                         label="一级指标">
        </el-table-column>
        <el-table-column min-width="20%"
                         prop="indicatorPointPlan"
                         label="指标要点">
        </el-table-column>
        <el-table-column
            prop="indicatorDetailPlan" min-width="47%"
            label="基本工作">
        </el-table-column>
        <el-table-column min-width="10%"
                         prop="endTimePlan"
                         label="计划完成时间">
        </el-table-column>
        <el-table-column min-width="8%"
                         prop="completePlan"
                         label="完成率">
        </el-table-column>
        <el-table-column min-width="5%"
                         prop="personInChargePlan" label="负责人"></el-table-column>
      </el-table-column>
    </el-table>
    <!--加减分项表-->
    <el-table :data="showScoreTable ? scoreTable : []" size="mini" border :span-method = "scoreTableSpanMethod"
              tooltip-effect="dark" header-cell-class-name="headerCell" style="width: 100%"
              header-row-class-name="headerRow" @cell-click="viewScoreItemDetail" :cell-style="cellStyle">
      <el-table-column label="党建加减分项">
        <template #header>
          <span>党建加减分项</span>
          <el-button
              type="text"
              size="mini"
              @click="showScoreTable = !showScoreTable"
          >
            <i :class="showScoreTable ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
            {{ showScoreTable ? '收起' : '展开' }}
          </el-button>
        </template>
        <el-table-column label="序号"
                         type="index"
                         min-width="5%" align="center"></el-table-column>
        <el-table-column min-width="14%"
                         prop="name"
                         label="类别"></el-table-column>
        <el-table-column prop="content" label="具体内容" min-width="81%"></el-table-column>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialogVisible" width="70%" :before-close="handleClose" :close-on-click-modal=false	>
      <el-empty description="暂无信息"></el-empty>
    </el-dialog>

    <!--custom表-->
    <el-table :data="showCustomKpiPlanTable ? customPrimaryIndicatorPlanVOS : []" size="min"
              tooltip-effect="dark" header-cell-class-name="headerCell"
              header-row-class-name="headerRow" style="width: 100%; margin-top: 20px;" @cell-click="viewKpiItemDetail"
              :cell-style="cellStyle">
      <el-table-column label="自定义党建工作计划">
        <template #header>
          <span>自定义党建工作计划</span>
          <el-button
              type="text"
              size="mini"
              @click="showCustomKpiPlanTable = !showCustomKpiPlanTable"
          >
            <i :class="showCustomKpiPlanTable ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
            {{ showCustomKpiPlanTable ? '收起' : '展开' }}
          </el-button>
        </template>
        <el-table-column label="序号"
                         type="index"
                         min-width="5%" align="center">
        </el-table-column>
        <el-table-column min-width="15%"
                         label="">
          <template slot-scope="scope">
            <el-input size="mini" v-model="scope.row.primaryIndicatorPlan" :disabled="!isTaskEditing"></el-input>
          </template>
        </el-table-column>
        <el-table-column min-width="20%"
                         label="">
          <template slot-scope="scope">
            <el-input size="mini" v-model="scope.row.indicatorPointPlan" :disabled="!isTaskEditing"></el-input>
          </template>
        </el-table-column>
        <el-table-column
            label="基本工作" prop="indicatorDetailPlan" min-width="47%">
          <template slot-scope="scope">
            <el-input size="mini" v-if="isTaskEditing" v-model="scope.row.indicatorDetailPlan"
                      @click.native.stop></el-input>
            <span v-else class="content-link"
                  @click="handleContentClick(scope.row, $event)">{{ scope.row.indicatorDetailPlan }}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="10%"
                         label="计划完成时间">
          <template slot-scope="scope">
            <el-input size="mini" v-model="scope.row.endTime" disabled></el-input>
          </template>
        </el-table-column>
        <el-table-column min-width="8%"
                         label="完成率">
          <template slot-scope="scope">
            <el-input size="mini" v-model="scope.row.complete" disabled></el-input>
          </template>
        </el-table-column>
        <el-table-column min-width="5%"
                         label="负责人">
          <template slot-scope="scope">
            <el-input size="mini" v-model="scope.row.personInCharge" disabled></el-input>
          </template>
        </el-table-column>
        <el-table-column min-width="5%">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="deleteTask(scope.row)"
                       :disabled="!isTaskEditing">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>


    <el-button size="mini" icon="el-icon-plus" type="text" @click="addCustomTask" :disabled="!isTaskEditing">增加党建工作计划
    </el-button>
    <el-button size="mini" icon="el-icon-edit" type="text" @click="editCustomTask" :disabled="!isPersonInCharge">编辑
    </el-button>
    <el-button size="mini" icon="el-icon-check" type="text" @click="submitCustomTask" :disabled="!isTaskEditing">提交
    </el-button>


  </el-card>
</template>

<script>

export default {
  name: "KPIDetail",
  data() {
    return {
      id: this.$route.params.id,
      kpiPartyVO: {},
      primaryIndicatorVOS: [],
      primaryIndicatorPlanVOS: [],
      scoreTable: [
        {name: '加分项', content: '1.年度内当选集团级及以上党、工、团、妇、统战会议代表。'},
        {name: '加分项', content: '2.年度内当选市区级及以上人大代表、政协委员、群团等组织的委员。'},
        {name: '加分项', content: '3.获得院及以上表彰荣誉、先进典型选树、优秀理论研究获奖成果。'},
        {name: '加分项', content: '4.在主流媒体刊发党建理论文章、署名文章等内容。'},
        {name: '加分项', content: '5.在院、集团、其他央企或上级机关交流党建工作经验、讲课或专题调研。'},
        {name: '加分项', content: '6.向院、集团及上级机关报送本年度的具有全局示范带动效应的党建工作创新实践经验、案例。'},
        {name: '加分项', content: '7.本年度对院党建工作支撑作用突出的。'},
        {name: '减分项', content: '1.单位主要领导涉嫌严重违纪违法被查处，或出现严重违纪造成严重不良影响被免职的。'},
        {name: '减分项', content: '2.现任班子成员因违纪违法在考核年度内受到严重警告及以上处分（或行政记大过及以上处分）。'},
        {name: '减分项', content: '3.本单位发生重大法律纠纷案件或重大风险事件。'},
        {name: '减分项', content: '4.因组织不力，导致重点经营指标完成不佳，或重点工作任务未按期完成，影响1号文完成或者造成严重后果的。'},
        {name: '减分项', content: '5.发生意识形态、质量、安全生产、保密、维稳等问题，造成严重后果的。'},
        {name: '减分项', content: '6.落实党员网络行为有关事项不力，发生党员网络违规行为，或员工违规违纪产生恶劣影响的。'},
        {name: '减分项', content: '7.有关材料弄虚作假，党建工作考核评价、巡视巡察、专项督查等发现问题后整改不力的。'},
        {name: '减分项', content: '8.发生其他造成严重不良影响情形的。'},
        {name: '减分项', content: '1.对院党委工作部署支撑不力的。 '},
        {name: '减分项', content: '2.高质量党建工作例会等党内会议请假频次较多，对工作落实产生影响的。'},
        {name: '减分项', content: '3.报告工作存在延期、不规范、不准确现象的。'},
      ],
      customPrimaryIndicatorPlanVOS: [],
      kpiDetailId: 0,//详情页中所选的kpi或者kpi计划项的id值
      title: '',
      showKpiTable: true,
      showKpiPlanTable: true,
      showCustomKpiPlanTable: true,
      showScoreTable: true,
      dialogVisible:false,
      isTaskEditing: false,
      isPersonInCharge: false
    }
  },
  methods:
      {
        treeToKpiTable(raw) {
          const result = []
          raw.primaryIndicatorVOS.forEach(primary => {
            primary.indicatorPointVOS.forEach(point => {
              point.indicatorDetailVOS.forEach(detail => {
                result.push({
                  primaryIndicator: primary.name,
                  indicatorPoint: point.name,
                  indicatorDetail: detail.content,
                  complete: detail.complete,
                  detailId: detail.id,
                  endTime: detail.endTime,
                  personInCharge: detail.personInCharge
                })
              })
            })
          })
          return result
        },
        treeToPlanTable(raw) {
          const result = []
          raw.primaryIndicatorPlanVOS.forEach(primary => {
            primary.indicatorPointPlanVOS.forEach(point => {
              point.indicatorDetailPlanVOS.forEach(detail => {
                result.push({
                  primaryIndicatorPlan: primary.name,
                  indicatorPointPlan: point.name,
                  indicatorDetailPlan: detail.content,
                  completePlan: detail.complete,
                  detailPlanId: detail.id,
                  endTimePlan: detail.endTime,
                  personInChargePlan: detail.personInCharge
                })
              })
            })
          })
          return result
        },
        treeToCustomPlanTable(raw) {
          const result = []
          raw.customPrimaryIndicatorPlanVOS.forEach(primary => {
            primary.customIndicatorPointPlanVOS.forEach(point => {
              point.customIndicatorDetailPlanVOS.forEach(detail => {
                result.push({
                  primaryIndicatorPlan: primary.name,
                  indicatorPointPlan: point.name,
                  indicatorDetailPlan: detail.content,
                  detailPlanId: detail.id,
                  endTime: detail.endTime,
                  complete: detail.complete,
                  personInCharge: detail.personInCharge,
                  primaryId: primary.id,
                  pointId: point.id,
                })
              })
            })
          })
          return result
        },
        // 党建KPI表格合并行方法
        kpiSpanMethod({row, column, rowIndex, columnIndex}) {
          // 0: 序号, 1: 一级指标, 2: 指标要点, 3: 具体内容, 4: 完成情况
          if (columnIndex === 1) { // 一级指标
            return this.getSpanInfo(this.primaryIndicatorVOS, rowIndex, 'primaryIndicator')
          }
          if (columnIndex === 2) { // 指标要点
            return this.getSpanInfo(this.primaryIndicatorVOS, rowIndex, 'primaryIndicator', 'indicatorPoint')
          }
          // 其他列不合并
          return {rowspan: 1, colspan: 1}
        },
        // 党建工作计划表格合并行方法
        planSpanMethod({row, column, rowIndex, columnIndex}) {
          // 0: 序号, 1: 一级指标, 2: 指标要点, 3: 基本工作
          if (columnIndex === 1) { // 一级指标
            return this.getSpanInfo(this.primaryIndicatorPlanVOS, rowIndex, 'primaryIndicatorPlan')
          }
          if (columnIndex === 2) { // 指标要点
            return this.getSpanInfo(this.primaryIndicatorPlanVOS, rowIndex, 'primaryIndicatorPlan', 'indicatorPointPlan')
          }
          // 其他列不合并
          return {rowspan: 1, colspan: 1}
        },
        // 增减分表格合并方法
        scoreTableSpanMethod({row, column, rowIndex, columnIndex}) {
          // 0: 序号, 1: name, 2: content
          if (columnIndex === 1) { // 一级指标
            return this.getSpanInfo(this.scoreTable, rowIndex, 'name')
          }
          // 其他列不合并
          return {rowspan: 1, colspan: 1}
        },
        // 自定义工作计划表格合并方法
        customPlanSpanMethod({row, column, rowIndex, columnIndex}) {
          // 0: 序号, 1: 一级指标, 2: 指标要点, 3: 基本工作
          if (columnIndex === 1) { // 一级指标
            return this.getSpanInfo(this.customPrimaryIndicatorPlanVOS, rowIndex, 'primaryIndicatorPlan')
          }
          if (columnIndex === 2) { // 指标要点
            return this.getSpanInfo(this.customPrimaryIndicatorPlanVOS, rowIndex, 'primaryIndicatorPlan', 'indicatorPointPlan')
          }
          // 其他列不合并
          return {rowspan: 1, colspan: 1}
        },
        // 通用合并行计算方法
        getSpanInfo(data, rowIndex, groupKey, subKey) {
          const currentRow = data[rowIndex]
          if (!currentRow) return {rowspan: 0, colspan: 0}

          const groupValue = currentRow[groupKey]
          const subValue = subKey ? currentRow[subKey] : null

          let firstRow = -1
          let count = 0

          data.forEach((item, idx) => {
            const matchGroup = item[groupKey] === groupValue
            const matchSub = !subKey || item[subKey] === subValue

            if (matchGroup && matchSub) {
              if (firstRow === -1) firstRow = idx
              count++
            }
          })

          if (rowIndex === firstRow) {
            return {rowspan: count, colspan: 1}
          } else {
            return {rowspan: 0, colspan: 0}
          }
        },
        viewKpiItemDetail(row, column, cell, event) {
          // 确保只处理特定列的点击
          if (column.property !== 'indicatorDetail' && column.property !== 'indicatorDetailPlan') {
            return;
          }

          // 根据数据源判断是哪个表格
          let type = '';
          if (this.primaryIndicatorVOS.includes(row)) {
            type = 'kpi';
          } else if (this.primaryIndicatorPlanVOS.includes(row)) {
            type = 'plan';
          } else if (this.customPrimaryIndicatorPlanVOS.includes(row)) {
            type = 'custom';
          } else {
            // 不属于任何表格的数据，直接返回
            return;
          }

          // 根据列属性区分title和id
          let title = '';
          let kpiDetailId = '';
          if (type === 'kpi' && column.property === 'indicatorDetail') {
            title = row.indicatorDetail;
            kpiDetailId = row.detailId;
          } else if ((type === 'plan' || type === 'custom') && column.property === 'indicatorDetailPlan') {
            title = row.indicatorDetailPlan;
            kpiDetailId = row.detailPlanId;
          } else {
            // 如果列和表格类型不匹配，不跳转
            return;
          }

          const kpiId = this.id;

          // 跳转
          this.$router.push({
            name: 'KPIItemScheme',
            query: {title, kpiDetailId, kpiId, type}
          });
        },
        viewScoreItemDetail(row, column, cell, event) {
          // 确保只处理特定列的点击
          if (column.property !== 'content') {
            return;
          }
          this.dialogVisible = true
        },
        handleClose(){
          this.dialogVisible = false
        },
        addCustomTask() {
          this.customPrimaryIndicatorPlanVOS.push({
            primaryIndicatorPlan: '',   // 第一列
            indicatorPointPlan: '',     // 第二列
            indicatorDetailPlan: '',             // 第三列
            endTime: '',
            complete: '',                    // 其他列
            personIncharge: ''
          })
        },
        deleteTask(row) {
          const index = this.customPrimaryIndicatorPlanVOS.indexOf(row);
          if (index > -1) {
            this.customPrimaryIndicatorPlanVOS.splice(index, 1);
          }
        },
// ✅ 生成后端 DTO 所需的树形数据（带 id）
    tableToTree(tableData) {
      const tree = []
      const primaryMap = new Map()

      tableData.forEach((row, idx) => {
        // 1) 一级（主指标）
        const pKey = row.primaryId ?? `NEW_P_${row.primaryIndicatorPlan}_${idx}`
        if (!primaryMap.has(pKey)) {
          primaryMap.set(pKey, {
            id: row.primaryId || null,      // ✨ 带上 id
            name: row.primaryIndicatorPlan, // 可被用户改名
            points: [],
          })
          tree.push(primaryMap.get(pKey))
        }
        const primaryRef = primaryMap.get(pKey)

        // 2) 二级（要点）—— 注意二级 map 需“挂在”各自的一级下面
        if (!primaryRef.__pointMap) primaryRef.__pointMap = new Map()
        const ptKey = row.pointId ?? `NEW_PT_${row.indicatorPointPlan}_${idx}`
        if (!primaryRef.__pointMap.has(ptKey)) {
          primaryRef.__pointMap.set(ptKey, {
            id: row.pointId || null,           // ✨ 带上 id
            name: row.indicatorPointPlan,
            details: [],
          })
          primaryRef.points.push(primaryRef.__pointMap.get(ptKey))
        }
        const pointRef = primaryRef.__pointMap.get(ptKey)

        // 3) 三级（内容）
        pointRef.details.push({
          id: row.detailPlanId || null,      // ✨ 带上 id
          content: row.indicatorDetailPlan,
          // 若后端 DTO 支持这些字段也可以一并带上：
          // endTime: row.endTime,
          // complete: row.complete,
          // personInCharge: row.personInCharge,
        })
      })

      // 清理内部 map
      tree.forEach(p => delete p.__pointMap)
      return tree
    },
    submitCustomTask() {
      if (this.customPrimaryIndicatorPlanVOS.length === 0) {
        this.$message.warning('请填入数据');
        return;
      }
      const kpiPartyReleaseDTO = {
        customPrimaryIndicatorPlanDTOS: this.tableToTree(this.customPrimaryIndicatorPlanVOS),
        id: this.id
      }
      console.log(JSON.stringify(kpiPartyReleaseDTO, null, 2))
      this.$http.post("/kpi/release/custom_task", kpiPartyReleaseDTO, {
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(response => {
        if (response.data.code == 1) {
          this.$message({
            type: 'success',
            message: "自定义工作发布成功",
            showClose: true,
          });
          this.isTaskEditing = false
        } else {
          this.$message({type: 'error', message: '发布失败:', showClose: true});
        }
      });
    },
    handleContentClick(row, event) {
      // 如果内容为空，阻止事件冒泡，允许输入
      if (!row.indicatorDetailPlan || row.indicatorDetailPlan.trim() === '') {
        event.stopPropagation();
      } else {
        // 如果有内容，调用跳转逻辑
        console.log(row)
        this.viewKpiItemDetail(row, {property: 'indicatorDetailPlan'});

      }
    },
    editCustomTask() {
      this.isTaskEditing = true
    },
    cellStyle({row, column, rowIndex, columnIndex}) {
      if (column.property == 'indicatorDetailPlan' || column.property == 'indicatorDetail' || column.property == 'content') {
        return {
          color: '#1989FA', // 蓝色文本
          textDecoration: 'none', // 下划线
          cursor: 'pointer', // 鼠标悬停时显示手型
        };
      }
      return {};
    },
  },
  mounted() {
    const user = JSON.parse(localStorage.getItem('user'))
    if (user.username === "mengqiang" || user.username === "cfswt") {
      this.isPersonInCharge = true
      console.log(user.nickName + this.isPersonInCharge)
    }
    this.$http.get(`/kpi/detail/${this.id}`).then((kpiRes) => {
      if (kpiRes.data.code == 1) {
        this.kpiPartyVO = kpiRes.data.data
        this.primaryIndicatorVOS = this.treeToKpiTable(this.kpiPartyVO)
        this.primaryIndicatorPlanVOS = this.treeToPlanTable(this.kpiPartyVO)
        this.customPrimaryIndicatorPlanVOS = this.treeToCustomPlanTable(this.kpiPartyVO)
        console.log(JSON.stringify(this.customPrimaryIndicatorPlanVOS, null, 2))
      }
    })
  }
}
</script>

<style scoped>
::v-deep .el-table {
  border: 1px solid #d1dbe5;
}

::v-deep .headerCell {
  text-align: center !important;
  font-weight: normal;
  font-size: 0.75rem !important;
  color: #545454;
}

::v-deep .headerRow {
  background: transparent !important;
}

::v-deep .content-link {
  color: #1989FA;
  text-decoration: underline;
  cursor: pointer;
}

</style>